<style lang="less" scoped>
@import "../../style/renyuanguanli/renyuanguanli.css";
</style>
<template>
  <div class="main">
    <div class="border-list">
      <!-- 查询输入框开始 -->
      <div class="roleInput">
        <span class="roleHint">角色名称:</span
        ><el-input v-model="roleinput" placeholder="角色名称查询"></el-input>
      </div>
      <div class="add-btn">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addVisible = true"
          class="addRoleBtn"
          >添加人员</el-button
        >
      </div>
      <div class="roleSerch">
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="query(roleinput)"
          >查询</el-button
        >
        <el-button type="primary" icon="el-icon-refresh-left" @click="onload()"
          >重置</el-button
        >
      </div>
      <div class="from-list">
        <el-table :data="tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)" border style="width: 100%" class="tab-list">
          <el-table-column
            align="center"
            type="index"
            prop="index"
            label="id"
            width="80px"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="username"
            label="用户名"
            width="150"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="nickname"
            label="用户昵称"
            width="100"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="phone"
            label="联系电话"
            width="120"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="department"
            label="部门"
            width="100"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="position"
            label="岗位"
            width="100"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="time"
            label="创建时间"
            width="180"
          >
          </el-table-column>
          <el-table-column align="center" label="Action" width="368">
            　<template slot-scope="scope">
              　　　　　　<el-button type="text" @click="checkDetail(scope.row)"
                >设置组织</el-button
              >
              　　　　　　<el-button type="text" @click="modifyUser(scope.row)"
                >设置角色</el-button
              >
              　　　　　　<el-button type="text" @click="setPassword(scope.row)"
                >重置密码</el-button
              >
              <el-button
                class="delete-btn"
                type="text"
                @click="deleteUser(scope.row)"
                ><a href="javascript:;" class="font">删除</a></el-button
              >
              　　　　</template
            >
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <!-- @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage4" -->
        <div class="fenye">
          <div class="block">
            <!-- <el-pagination
              background
               :current-page="queryinfo.pagenum" 
              :page-sizes="[1, 2, 5, 10]"
              :page-size="queryInfo.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
            >
            </el-pagination> -->

             <el-pagination
            :page-size="4"
            :current-page.sync="currentPage"
            :page-sizes="[4, 8]"
            layout="total,sizes,prev,pager,next,jumper"
            :hide-on-single-page="false"
            :total="total"
            @size-change="sizeChange"
          ></el-pagination>
                </div>
        </div>
        <!-- 添加人员弹窗 -->
        <div class="tianjiauser">
          <el-dialog
            :title="dialogtitle"
            :close-on-click-modal="false"
            :visible.sync="addVisible"
            width="500px"
          >
            <el-form ref="form" :model="form" :rules="rules">
              <el-form-item
                label="账户名称 :"
                :label-width="formLabelWidth"
                placeholder="请输入账户名称"
                prop="username"
                :value="form.username"
              >
                <el-input autocomplete="off" v-model="form.username"></el-input>
              </el-form-item>
              <el-form-item
                label="账户昵称 :"
                :label-width="formLabelWidth"
                placeholder="请输入账户昵称"
                prop="nickname"
                :value="form.nickname"
              >
                <el-input autocomplete="off" v-model="form.nickname"></el-input>
              </el-form-item>
              <el-form-item
                label="手机号码 :"
                :label-width="formLabelWidth"
                placeholder="请输入手机号"
                prop="phone"
                :value="form.phone"
              >
                <el-input autocomplete="off" v-model="form.phone"></el-input>
              </el-form-item>
              <el-form-item
                label="账户密码 :"
                :label-width="formLabelWidth"
                placeholder="请输入账户密码"
                prop="password"
                :value="form.password"
              >
                <el-input autocomplete="off" v-model="form.password"></el-input>
              </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
              <el-button @click="cancel()">取 消</el-button>
              <el-button type="primary" @click="addUser(form)">确 定</el-button>
            </div>
          </el-dialog>
        </div>
        <!-- *********************************************************************** -->
        <!-- 设置组织  弹出框内容 -->
        <div class="ys-dialog">
          <el-dialog
            title="编辑 管理员组织"
            :visible.sync="dialogFormVisible"
            :before-close="handleClose"
            width="500px"
          >
            <el-form :model="organize" ref="organize">
              <el-form-item label="账户名称 :" :label-width="formLabelWidth">
                <el-input
                  v-model="organize.nickname"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item label="手机号码 :" :label-width="formLabelWidth">
                <el-input
                  v-model="organize.phone"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item label="组织部门 :" :label-width="formLabelWidth">
                <el-select
                  v-model="organize.department"
                  placeholder="请选择组织部门"
                >
                  <el-option label="开发部" value="开发部"></el-option>
                  <el-option label="运营部" value="运营部"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="组织职位 :" :label-width="formLabelWidth">
                <el-radio-group v-model="organize.position">
                  <el-radio label="普通"></el-radio>
                  <el-radio label="组长"></el-radio>
                  <el-radio label="经理"></el-radio>
                </el-radio-group>
              </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取 消</el-button>
              <el-button type="primary" @click="setorganization(organize)"
                >确 定</el-button
              >
            </div>
          </el-dialog>
        </div>
        <!-- 设置角色    -->
        <div class="setsRole">
          <el-dialog
            title="设置角色"
            :visible.sync="setRole"
            width="50%"
            :before-close="handleClose"
            class="setRole"
          >
            <el-transfer v-model="value" :data="data"> </el-transfer>
            <span slot="footer" class="dialog-footer">
              <el-button @click="setRole = false">取 消</el-button>
              <el-button type="primary" @click="setUpdaetRole(value)"
                >确 定</el-button
              >
            </span>
          </el-dialog>
        </div>
        <!-- 重置密码    -->
        <div class="ys-password">
          <el-dialog
            title="重置 管理员密码"
            :visible.sync="setpwdVisible"
            :before-close="handleClose"
            width="500px"
          >
            <el-form :model="pass" :rules="rules" ref="pass">
              <el-form-item
                v-model="pass.passwordOne"
                :value="pass.passwordOne"
                prop="password"
                label="新密码 :"
                :label-width="formLabelWidth"
              >
                <el-input
                  :type="passForm.show.new ? 'text' : 'password'"
                  v-model="pass.passwordOne"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
              <el-button @click="quXiaoUpdata()">取 消</el-button>
              <el-button
                type="primary"
                @click="setDeltePassword(pass.passwordOne)"
                >确 定</el-button
              >
            </div>
          </el-dialog>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  apiAddress,
  apiGetUser,
  apiAddUser,
  apiSetorganization,
  apiSetRole,
  apiUpdatepass,
  apiRemoveUser,
} from "@/api/user"; // 导入我们的api接口
export default {
  data() {
    const generateData = (_) => {
      const data = [];
      const clientType = ["系统管理员", "商户", "省代", "市代"];
      clientType.forEach((client, index) => {
        data.push({
          label: client,
          key: index + 1,
        });
      });

      return data;
    };
    return {
      setRoot: {},
      columnkey: "",
      value: [],
      data: generateData(),
      roleinput: "",
      addVisible: false,
      setpwdVisible: false,
      dialogFormVisible: false,
      roleLimitdialogFormVisible: false,
      setRole: false,
      dialogtitle: "添加 管理员",
      formLabelWidth: "90px",
      userList: [],
      // 添加人员
      form: {
        username: "",
        nickname: "",
        phone: "",
        password: "",
      },
      // 设置组织
      organize: {
        id: "",
        nickname: "",
        phone: "",
        department: "",
        position: "",
      },
      // 修改密码
      pass: {
        passwordOne: "",
      },
      rules: {
        username: [
          {
            min: 6,
            max: 16,
            required: true,
            message: "请输入6-16位数字或字母",
            trigger: "blur",
          },
        ],
        nickname: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          { message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
        password: [
          {
            min: 6,
            max: 16,
            required: true,
            message: "请输入6-16位数字或字母",
            trigger: "blur",
          },
        ],
      },
      // 总条数
       total: 0,
      pageSize: 4,
      currentPage: 1,
      tableData: [],
      //密码隐藏条件
      passForm: {
        show: {
          old: false,
          check: false,
        },
      },
    };
  },
  mounted() {
    this.onload();
  },

  methods: {
    //获取全部用户
    onload() {
      apiGetUser({}).then((res) => {
        console.log(res);
        this.total=res.success.length
        this.tableData = res.success;
        this.tableData.forEach((doc) => {
          //更改时间格式
          doc.time = this.dayjs(doc.time).format("YYYY-MM-DD HH:mm:ss");
        });
      });
    },
    //通过昵称查询用户
    query(val) {
      console.log(val);
      if (val == "") {
        this.$message({
          message: "请输入用户信息",
          type: "info",
          duration: 1000,
        });
      } else {
        apiAddress({
          nickname: val,
        }).then((res) => {
          console.log(res.success);
          this.tableData = res.success;
          this.tableData.forEach((doc) => {
            //更改时间格式
            doc.time = this.dayjs(doc.time).format("YYYY-MM-DD HH:mm:ss");
          });
        });
      }
    },
    addUser(val) {
      var arr = Object.values(val).filter(function (item) {
        if (item !== "") {
          return true; //过滤掉为空的项
        }
      });
      if (arr.length === 0) {
        // 如果过滤后的arr长度为0，表示对象的键值对的值都为空！
        this.$message({
          message: "请输入用户信息",
          type: "info",
          duration: 1000,
        });
      } else {
        apiAddUser(val)
          .then((res) => {
            if (res.code == 200) {
              this.onload();
              // dialog中的表单取消提交
              this.addVisible = false;
              this.$nextTick(() => {
                this.$refs.form.resetFields();
                this.$message({
                  message: "创建成功",
                  type: "success",
                  duration: 1000,
                });
              });
            }
          })
          .catch((err) => {
            reject(err.data);
            this.$message({
              message: "创建失败",
              type: "info",
              duration: 1000,
            });
          });
      }
    },
  
    cancel() {
      // dialog中的表单取消提交
      this.addVisible = false;
      this.setpwdVisible = false;
      this.$nextTick(() => {
        this.$refs.form.resetFields();
      });
    },
    //  设置组织
    checkDetail(val, org) {
      this.dialogFormVisible = true;
      console.log(val._id, org);
      this.columnkey = val._id;
      this.$nextTick(() => {
        this.$refs.organize.resetFields();
      });
    },
    // 设置组织请求数据
    setorganization(val) {
     
      let arr = this.filterObj(val);
      if (arr.length == 0) {
        this.$message({
          message: "请输入用户信息",
          type: "info",
          duration: 1000,
        });
      } else {
        val.id = this.columnkey;
        apiSetorganization(val)
          .then((res) => {
            if (res.code == 200) {
              this.organize = {};
              this.onload();
              this.$message({
                message: "设置成功",
                type: "success",
                duration: 1000,
              });
               this.dialogFormVisible = false;
            }
          })
          .catch((err) => {
            this.$message({
              message: "设置失败",
              type: "info",
              duration: 1000,
            });
          });
      }
    },
    // 设置角色
    modifyUser(val) {
      this.setRole = true;
      this.columnkey = val._id;
    },
    // 设置角色请求
    setUpdaetRole(val) {
      this.setRole = false;
      let arr = this.filterObj(val);

      if (arr.length == 0) {
        this.$message({ message: "请选择信息", type: "info", duration: 1000 });
      } else {
        this.setRoot = {
          root: val[0],
        };
        (this.setRoot.id = this.columnkey),
          apiSetRole(this.setRoot)
            .then((res) => {
              this.$message({
                message: "设置成功",
                type: "success",
                duration: 1000,
              });
            })
            .catch((err) => {
              this.$message({
                message: "设置失败",
                type: "info",
                duration: 1000,
              });
            });
      }
    },
    //重置密码
    setPassword(val) {
      this.setpwdVisible = true;
      this.columnkey = val._id;
    },
    // 取消修改
    quXiaoUpdata() {
      this.setpwdVisible = false;
      this.pass = {};
    },
    setDeltePassword(val) {
      this.setpwdVisible = false;
      let arr = this.filterObj(val);
      if (arr.length == 0) {
        this.$message({ message: "请选择信息", type: "info", duration: 1000 });
      } else {
        let obj = {
          password: val,
        };
        (obj.id = this.columnkey),
          apiUpdatepass(obj)
            .then((res) => {
              this.pass = {};
              this.$message({
                message: "设置成功",
                type: "success",
                duration: 1000,
              });
            })
            .catch((err) => {
              this.$message({
                message: "设置失败",
                type: "info",
                duration: 1000,
              });
            });
      }
    },
    // 删除账号
        deleteUser(val){
          if(val){
            apiRemoveUser({
                id:val._id
              }).then(res=>{
                 this.$message({
                message: "删除成功",
                type: "success",
                duration: 2000,
                });
                this.onload()
              })
          }else{
             this.$message({
                message: "删除失败",
                type: "info",
                duration: 2000,
              }); 
          }
              
        },

    //关闭时确认弹框
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    //  分页
    sizeChange(val) {
      this.pageSize = val;
    },
    filterObj(val) {
      var arr = Object.values(val).filter(function (item) {
        if (item !== "") {
          return true; //过滤掉为空的项
        }
      });
      return arr;
    },
  },
};
</script>